//
//  OrderProductDetailVC.m
//  sensen_ios
//
//  Created by mc on 16/2/27.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "OrderProductDetailVC.h"

//选择退款
#import "OrderRefundVC.h"
#import "OrderPayRequestHandle.h" // 支付
#import "PayOrderModel.h" // 支付订单model

#import "ConfirmPayVC.h"



#import "OrderProductDetailCell.h"
#import "OrderProductCell.h"

#import "OrderAddressCell.h"

#import "OrderModel.h"
#import "CartProductModel.h"

@interface OrderProductDetailVC ()<UITableViewDataSource, UITableViewDelegate>{
    OrderModel * _model;
}
   



@property (nonatomic, strong) UITableView *tableView; // 表视图




@end

@implementation OrderProductDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"订单详情";
    // 创建导航栏左边返回按钮
    [self createLeftBarButtonItemWithImagename:nil];
    [self _initTableView];
    [self requestOrderDetail];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
}



// 创建表视图
- (void)_initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT  - 64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [BoyeTool colorFromHexRGB:@"#f5f5f5"];//rgba(235, 235, 235, 1);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
}

- (void)_initFooterView {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    footerView.backgroundColor = rgba(237, 238, 239, 1);
    UIButton  * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, _tableView.bottom, SCREEN_WIDTH, SCREEN_WIDTH / 8);
    [footerView addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView).offset(50);
        make.centerX.equalTo(footerView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH * 0.8, SCREEN_WIDTH / 12));
        
    }];
    [saveBtn setTitle:@"拨打电话" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(phoneAction:) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.layer.borderColor = SS_NAVI_ORANGE_COLOR.CGColor;
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.layer.borderWidth = 1;
    saveBtn.layer.masksToBounds = YES;
    saveBtn.layer.cornerRadius = 3.0;
    [saveBtn setBackgroundColor:SS_NAVI_ORANGE_COLOR];

}



//订单详情查询
- (void)requestOrderDetail{
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    [diction setObject:self.order_id forKey:@"id"];
    [SVProgressHUD showWithStatus:@"正在加载...."]; // 请求中
    [BoyeHttpClient post:@"BY_Orders_detail" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"%@", result);
        _tableView.hidden = NO;
        _model = [[OrderModel alloc] initContentWithDic:result];
        _model.order_id = result[@"id"];
        _model._items = [NSMutableArray array];
        NSMutableArray * items = result[@"items"];
        for (int i = 0; i < items.count; i++) {
            NSDictionary *itemsDic = [items objectAtIndex:i];
            CartProductModel *item = [[CartProductModel alloc] initContentWithDic:itemsDic];
            [_model._items addObject:item];
        }
        //请求物流信息
        //[self requestOrderExpress];
         [self.tableView reloadData];
         [SVProgressHUD dismiss];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
    }];
}

//获取订单物流信息
- (void)requestOrderExpress{
    NSLog(@"获取订单物流信息");
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:self.order_id forKey:@"order_code"];
    [BoyeHttpClient post:@"BY_Orders_express" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        
        
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

}





#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
   
    if (section == 1) {
        
//        if (([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 0) ||(([_model.order_status integerValue] == 2 || [_model.order_status integerValue] == 3 )&& [_model.pay_status integerValue] == 1)) {//待付款或者待发货 没有物流信息
//            return 1;
//        }else{
            return 1;
//        }
        
        
    }else if (section == 2){
        
//        if (([_model.order_status integerValue] == 5 && [_model.pay_status integerValue] == 1) || ([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 0)){//交易完成 或者待付款
//            
//            return _model._items.count + 1;
//            
//        }else{
            return _model._items.count + 1;
//        }
        
    }else{
        return 1;
    }
}

// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
     NSLog(@"%@ %@",_model.order_status, _model.pay_status);
    
    if (indexPath.section == 2) {
//        if (([_model.order_status integerValue] == 5 && [_model.pay_status integerValue] == 1) || ([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 0)){//交易完成 或者 待付款
        
            if (indexPath.row == _model._items.count) {
                
                static NSString * cellIdentifier = @"Cell2";
                UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
                if (cell ==nil) {
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                }
                
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [cell addSubview:button];
                [button mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(cell.mas_centerY);
                    make.right.equalTo(cell).offset(-10);
                    make.size.mas_equalTo(CGSizeMake(100, 30));
                    
                }];
                
                button.backgroundColor = SS_NAVI_ORANGE_COLOR;
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                
                
                if ([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 0) {
                    [button setTitle:@"付款" forState:UIControlStateNormal];
                }else{
                     [button setTitle:@"申请售后" forState:UIControlStateNormal];
                }
                
                
                [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
                /* 忽略点击效果 */
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                return cell;
                
            }else{
                OrderProductCell *cell = [OrderProductCell cellWithTableView:tableView];
                CartProductModel * item = [_model._items objectAtIndex:indexPath.row];
                [cell.ivContent setImageURLStr:item.img_url placeholder:DEFAULT_IMAGE];
                cell.lblTitle.text = item.name;
                cell.lblBrand.text = item.sku_desc;
                cell.lblPrice.text = [NSString stringWithFormat:@"¥%@", item.price];
                cell.lblCount.text = [NSString stringWithFormat:@"X %@", item.count];
                /* 忽略点击效果 */
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                return cell;
            }
            
//        }else{
//            OrderProductCell *cell = [OrderProductCell cellWithTableView:tableView];
//            CartProductModel * item = [_model._items objectAtIndex:indexPath.row];
//            [cell.ivContent setImageURLStr:item.img_url placeholder:DEFAULT_IMAGE];
//            cell.lblTitle.text = item.name;
//            cell.lblBrand.text = item.sku_desc;
//            cell.lblPrice.text = item.price;
//            cell.lblCount.text = [NSString stringWithFormat:@"X %@", item.count];
//            return cell;
//
//        }

    }else if (indexPath.section == 1){
        
        if (indexPath.row == 0) {
            
            
            
//            if (([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 0) ||(([_model.order_status integerValue] == 2 || [_model.order_status integerValue] == 3)&& [_model.pay_status integerValue] == 1)) {//待付款或者待发货 没有物流信息
                OrderAddressCell *cell = [OrderAddressCell cellWithTableView:tableView];
                cell.model = _model;
                return cell;
//
//            }else{
//                static    NSString  * identifier = @"cell";
//                UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//                if (cell == nil) {
//                    cell = [[UITableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
//                    
//                }
//                
//                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//                for (UIView *view in cell.subviews) {
//                    [view removeFromSuperview];
//                }
//                
//                
//                UIImageView * imageView = [[UIImageView alloc] init];
//                imageView.image = [UIImage imageNamed:@"订单详情_物流"];
//                [cell addSubview:imageView];
//                [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.equalTo(cell).offset(10);
//                    make.centerY.equalTo(cell.mas_centerY).offset(0);
//                    make.size.mas_equalTo(CGSizeMake(20, 25));
//                }];
//                
//                
//                
//                UILabel *  addressLable = [[UILabel alloc] init];
//                [cell addSubview:addressLable];
//                addressLable.font = FONT(14);
//                addressLable.text = [NSString stringWithFormat:@"%@%@%@%@",_model.province,_model.city,_model.area,_model.detailinfo];
//                
//                [addressLable mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.equalTo(imageView.mas_right).offset(10);
//                    make.top.equalTo(cell).offset(10);
//                    make.right.equalTo(cell).offset(-50);
//                    make.height.mas_equalTo(@35);
//                }];
//                
//                addressLable.numberOfLines = 2;
//                addressLable.textColor = rgba(29, 169, 52, 1);
//                
//                UILabel *  timeLable = [[UILabel alloc] init];
//                [cell addSubview:timeLable];
//                timeLable.font = FONT(12);
//                [timeLable mas_makeConstraints:^(MASConstraintMaker *make) {
//                    make.left.equalTo(addressLable.mas_left).offset(0);
//                    make.bottom.equalTo(cell).offset(-5);
//                    make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 150, 15));
//                }];
//                timeLable.text = [NSDate getDateStringFromeNumber:_model.updatetime];
//                timeLable.textColor = [UIColor lightGrayColor];
//                
//                
//                
//                
//                return cell;
//            }
//
        }else{
            OrderAddressCell *cell = [OrderAddressCell cellWithTableView:tableView];
            cell.model = _model;
            /* 忽略点击效果 */
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            return cell;
        }
    }else{
        static    NSString  * identifier = @"cell";
        UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        
          for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
          }
            UIView * view = [[UIView alloc] init];
            [cell.contentView addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(cell.contentView).offset(50);
                make.centerY.equalTo(cell.contentView.mas_centerY).offset(0);
                make.size.mas_equalTo(CGSizeMake(150, 50));
            }];
            
            //等待卖家付款
            UILabel * statelable = [[UILabel alloc] init];
            [view addSubview:statelable];
            [statelable mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(view).offset(0);
                make.right.equalTo(view).offset(0);
                make.top.equalTo(view).offset(0);
                make.height.mas_equalTo(@30);
            }];
            
            statelable.textColor = SS_NAVI_ORANGE_COLOR;
            statelable.font = FONT(20);
            //还剩6天9时自动关闭
            UILabel * timelable = [[UILabel alloc] init];
            [view addSubview:timelable];
            [timelable mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(view).offset(0);
                make.right.equalTo(view).offset(0);
                make.bottom.equalTo(view).offset(0);
                make.height.mas_equalTo(@20);
            }];
            timelable.textColor = SS_NAVI_ORANGE_COLOR;
            timelable.font = FONT(14);
            
            //状态图片
            UIImageView * imageView = [[UIImageView alloc] init];
            [cell.contentView addSubview:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(cell.contentView).offset(-50);
                make.centerY.equalTo(cell.contentView.mas_centerY).offset(0);
                make.size.mas_equalTo(CGSizeMake(100, 80));
            }];
            
            
            //NSArray * imageItems = @[@"订单详情-交易成功_03",@"订单详情_已发货",@"订单详情-代付款_03",@"订单详情-代发货_03"];
            
            
            //待付款
            if ([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 0) {
                
                imageView.image = [UIImage imageNamed:@"订单详情-代付款_03"];
                statelable.text = @"等待买家付款";
                //timelable.text = @"还剩6天9时自动确认";

                
            }
            //待收货状态
            else if ([_model.order_status integerValue] == 4 && [_model.pay_status integerValue] == 1){
                imageView.image = [UIImage imageNamed:@"订单详情_已发货"];
                statelable.text = @"卖家已发货";
                //timelable.text = @"还剩6天9时自动确认";

            //交易完成
            }else if ([_model.order_status integerValue] == 5 && [_model.pay_status integerValue] == 1){
                
                imageView.image = [UIImage imageNamed:@"订单详情-交易成功_03"];
                statelable.text = @"交易完成";
             //待发货
            }else if (([_model.order_status integerValue] == 2 || [_model.order_status integerValue] == 3)&& [_model.pay_status integerValue] == 1){
                
                imageView.image = [UIImage imageNamed:@"订单详情-代发货_03"];
                statelable.text = @"买家已付款";
            }else if ([_model.pay_status integerValue] == 2){
                statelable.text = @"交易完成";
            }else{
                imageView.image = [UIImage imageNamed:@"订单详情-交易成功_03"];
                statelable.text = @"交易完成";
            }

        
        
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        return cell;
    }
}

// 设置单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        return 70;
    }else if(indexPath.section == 2){
        if (indexPath.row == _model._items.count) {
            return 44;
        }else{
            return 75;
        }
    }else{
        return 100;
    }
    
}

// 设置组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
   
    if (section == 0) {
        return 5;
    }else{
        return 5;
    }
}


-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 2) {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 100)];
        footerView.backgroundColor = rgba(237, 238, 239, 1);
        UIButton  * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        saveBtn.frame = CGRectMake(0, _tableView.bottom, SCREEN_WIDTH, SCREEN_WIDTH / 8);
        [footerView addSubview:saveBtn];
        [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(footerView).offset(50);
            make.centerX.equalTo(footerView.mas_centerX);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH * 0.8, SCREEN_WIDTH / 12));
            
        }];
        [saveBtn setTitle:@"拨打电话" forState:UIControlStateNormal];
        [saveBtn addTarget:self action:@selector(phoneAction:) forControlEvents:UIControlEventTouchUpInside];
        saveBtn.layer.borderColor = SS_NAVI_ORANGE_COLOR.CGColor;
        [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        saveBtn.layer.borderWidth = 1;
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 3.0;
        
        [saveBtn setBackgroundColor:SS_NAVI_ORANGE_COLOR];
        
        return footerView;

    }else{
        
        return nil;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 2) {
        return 100;
    }else{
        return 5;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    
    if (([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 0) ||([_model.order_status integerValue] == 2 && [_model.pay_status integerValue] == 1)) {//待付款或者待发货 没有物流信息
       
    }else{
        if (indexPath.section == 1 && indexPath.row == 0) {
            
           
        }
    }

    
    
    

}

- (void)buttonAction:(UIButton *)button{
    NSString *title = [button titleForState:UIControlStateNormal];
    if ([title isEqualToString:@"售后"]) {
          }
    else if ([title isEqualToString:@"申请售后"]){
        OrderRefundVC *vc = [[OrderRefundVC alloc] init];
        vc.model = _model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if ([title isEqualToString:@"付款"]){
       
        NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
        UserModel *user = [CommonCache getUserInfo];
        [diction setObject:user.uid forKey:@"uid"];
        [diction setObject:_model.order_id forKey:@"order_id"];
        [BoyeHttpClient post:@"BY_Orders_pay" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
            NSLog(@"%@" , result);
            [SVProgressHUD dismiss];
            // 创建支付订单model
            PayOrderModel *payOrderModel = [[PayOrderModel alloc] initContentWithDic:result];
            // 添加订单成功后，跳转到选择支付页面
            ConfirmPayVC *vc = [[ConfirmPayVC alloc] init];
            vc.payOrderModel = payOrderModel;
            [self.navigationController pushViewController:vc animated:YES];
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:1];
        }];

        
        
        
        
    }

}

- (void)phoneAction:(UIButton *)button{
    
    if (_model.service_phone.length > 0) {
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_model.service_phone];
        UIWebView * callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
        [self.view addSubview:callWebview];
    }else{
         [SVProgressHUD showOnlyStatus:@"电话号码为空，请联系客服" withDuration:1];
    }

 }

#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
